package com.example.newhabitclock.TimeAdd

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

// Data class for a mark entry
data class Mark(val number: Int, val timeDifference: Long, val absoluteTime: Long)

// Enum for stopwatch states
enum class StopwatchState {
    STOPPED, RUNNING, PAUSED
}

class StopwatchViewModel : ViewModel() {
    // Stopwatch state
    private var state: StopwatchState = StopwatchState.STOPPED
    private val _stateLiveData = MutableLiveData<StopwatchState>(StopwatchState.STOPPED)
    val stateLiveData: LiveData<StopwatchState> = _stateLiveData

    // Timing variables (in milliseconds)
    private var elapsedTime: Long = 0 // Total elapsed time when paused
    private var startTime: Long = 0  // Time when started or resumed

    // Marks list
    private val marks = mutableListOf<Mark>()
    private val _marksLiveData = MutableLiveData<List<Mark>>(emptyList())
    val marksLiveData: LiveData<List<Mark>> = _marksLiveData

    // Start the stopwatch
    fun start() {
        if (state == StopwatchState.STOPPED) {
            startTime = System.currentTimeMillis()
            state = StopwatchState.RUNNING
            _stateLiveData.value = StopwatchState.RUNNING
        }
    }

    // Pause the stopwatch
    fun pause() {
        if (state == StopwatchState.RUNNING) {
            elapsedTime += System.currentTimeMillis() - startTime
            state = StopwatchState.PAUSED
            _stateLiveData.value = StopwatchState.PAUSED
        }
    }

    // Resume the stopwatch
    fun resume() {
        if (state == StopwatchState.PAUSED) {
            startTime = System.currentTimeMillis()
            state = StopwatchState.RUNNING
            _stateLiveData.value = StopwatchState.RUNNING
        }
    }

    // Reset the stopwatch
    fun reset() {
        if (state == StopwatchState.PAUSED) {
            state = StopwatchState.STOPPED
            elapsedTime = 0
            marks.clear()
            _marksLiveData.value = marks
            _stateLiveData.value = StopwatchState.STOPPED
        }
    }

    // Add a mark when running
    fun addMark() {
        if (state == StopwatchState.RUNNING) {
            val currentTime = getCurrentDisplayTime()
            val markNumber = marks.size + 1
            val lastMarkTime = if (marks.isEmpty()) 0 else marks.first().absoluteTime
            val timeDifference = currentTime - lastMarkTime
            val mark = Mark(markNumber, timeDifference, currentTime)
            marks.add(0, mark) // Insert at the beginning for newest-first order
            _marksLiveData.value = marks
        }
    }

    // Get the current display time based on state
    fun getCurrentDisplayTime(): Long {
        return when (state) {
            StopwatchState.STOPPED -> 0
            StopwatchState.RUNNING -> elapsedTime + (System.currentTimeMillis() - startTime)
            StopwatchState.PAUSED -> elapsedTime
        }
    }
}